package com.example.gulimall.common.utils;

import com.alibaba.druid.util.StringUtils;
import com.example.gulimall.common.enums.ServiceCodeEnum;
import com.example.gulimall.common.exceptions.ApiException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

/**
 * @author future
 * @since 1.0
 */
@Slf4j
public class ObjectMapperKit {
    private static ObjectMapper sMapper = new ObjectMapper();

    static {
        sMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        sMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    /**
     * 将json字符串转化成java类
     *
     * @param json
     * @param clz
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> T toObject(String json, Class<T> clz) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }

        T t = null;
        try {
            t = sMapper.readValue(json, clz);
        } catch (IOException e) {
            log.error("parse string to bean failed: ", e);
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(), e.getMessage());
        }

        return t;
    }

    /**
     * 将输入流转换成java类
     *
     * @param is
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T toObject(InputStream is, Class<T> clazz) {
        T t = null;
        try {
            t = sMapper.readValue(is, clazz);
        } catch (IOException e) {
            log.error("parse InputStream to bean failed: ", e);
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(), e.getMessage());
        }
        return t;
    }

    /**
     * 将java类转换成json字符串
     *
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String toJson(T obj) {
        StringWriter sw = new StringWriter();
        try {
            sMapper.writeValue(sw, obj);
        } catch (Exception e) {
            log.error("parse json to string failed: ", e);
            throw new ApiException(ServiceCodeEnum.SERVER_INTERNAL_ERROR.getCode(), e.getMessage());
        }

        return sw.toString();
    }

}
